//
//  CollectManager.m
//  quanminzhekou
//
//  Created by zxl on 15/1/22.
//  Copyright (c) 2015年 zhongqinglongtu. All rights reserved.
//

#import "CollectManager.h"

@implementation CollectManager

+ (NSString*)pathOfDataFile {
    static NSString* s_pathOfDataFile = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        s_pathOfDataFile = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"CollectManager.data"];
//        NSLog(@"s_pathOfDataFile:%@", s_pathOfDataFile);
    });
    
    return s_pathOfDataFile;
}

+ (CollectManager*)shareManager {
    static CollectManager* s_collectManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        @try {
            s_collectManager = [NSKeyedUnarchiver unarchiveObjectWithFile:[self pathOfDataFile]];
        }
        @catch (NSException *exception) {
            [[NSFileManager defaultManager] removeItemAtPath:[self pathOfDataFile] error:nil];
        }
        @finally {
            if (nil == s_collectManager) {
                s_collectManager = [[CollectManager alloc] init];
            }
        }
    });
    
    return s_collectManager;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _collectArr = [[NSMutableArray alloc] init];
    }
    
    return self;
}

- (void)synchronize {
    [NSKeyedArchiver archiveRootObject:self toFile:[self.class pathOfDataFile]];
}

- (BOOL)isCollectedGoods:(CommonCellViewModel*)goods {
    if ([goods isKindOfClass:[CommonCellViewModel class]]) {
        for (CommonCellViewModel* collect in self.collectArr) {
            if ([collect.goodsID isEqualToString:goods.goodsID]) {
                return YES;
            }
        }
    }
    
    return NO;
}

- (void)addCollectedGoods:(CommonCellViewModel*)goods {
    if ([goods isKindOfClass:[CommonCellViewModel class]]) {
        if (![self isCollectedGoods:goods]) {
            [self.collectArr addObject:goods];
            [self synchronize];
        }
    }
}

- (void)removeCollectGoods:(CommonCellViewModel*)goods {
    if ([goods isKindOfClass:[CommonCellViewModel class]]) {
        for (CommonCellViewModel* collect in self.collectArr) {
            if ([collect.goodsID isEqualToString:goods.goodsID]) {
                [self.collectArr removeObject:collect];
                [self synchronize];
                break;
            }
        }
    }
}

#pragma mark - NSCoding
- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:self.collectArr forKey:@"collectArr"];
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];
    if (self) {
        self.collectArr = [aDecoder decodeObjectForKey:@"collectArr"];
    }
    
    return self;
}

@end
